<template>
    <x-search
        :collapsed="collapsed"
        :columns="{ sm: 1, md: 2, lg: 3, xl: 3, xxl: 4 }"
        :label-col="{ style: { width: '80px' } }"
        :model="searchFormData">
        <x-search-item
            label="单位名称"
            name="companyName">
            <a-input v-model:value="searchFormData.companyName"></a-input>
        </x-search-item>
        <x-search-item
            label="信用代码"
            name="creditCode">
            <a-input v-model:value="searchFormData.creditCode"></a-input>
        </x-search-item>
        <x-search-item
            label="报出日期"
            :name="tableIndex == 0 ? (curList.includes('0') ? 'year' : 'month') : 'period'">
            <a-input
                v-model:value="
                    searchFormData[tableIndex == 0 ? (curList.includes('0') ? 'year' : 'month') : 'period']
                "></a-input>
        </x-search-item>
        <x-search-item
            class="align-right"
            suffix>
            <a-space>
                <a-button @click="handleReset">重置</a-button>
                <a-button
                    ghost
                    type="primary"
                    @click="handleSearch">
                    搜索
                </a-button>
                <a @click="() => (collapsed = !collapsed)">
                    展开
                    <template v-if="collapsed">
                        <down-outlined class="fs-12"></down-outlined>
                    </template>
                    <template v-else>
                        <up-outlined class="fs-12"></up-outlined>
                    </template>
                </a>
            </a-space>
        </x-search-item>
    </x-search>
    <a-card class="mt-8-2">
        <x-toolbar v-if="false">
            <a-button
                type="primary"
                @click="$refs.editDialogRef.handleCreate()">
                <template #icon>
                    <plus-outlined></plus-outlined>
                </template>
                新建
            </a-button>
            <template #extra>
                <a-space>
                    <a-tooltip title="刷新">
                        <a-button
                            type="text"
                            @click="handleSearch">
                            <template #icon>
                                <reload-outlined></reload-outlined>
                            </template>
                        </a-button>
                    </a-tooltip>
                    <a-dropdown>
                        <a-tooltip title="密度">
                            <a-button type="text">
                                <template #icon>
                                    <column-height-outlined></column-height-outlined>
                                </template>
                            </a-button>
                        </a-tooltip>
                        <template #overlay>
                            <a-menu
                                :selectedKeys="[size]"
                                @click="handleSize">
                                <a-menu-item key="default">默认</a-menu-item>
                                <a-menu-item key="middle">中等</a-menu-item>
                                <a-menu-item key="small">紧凑</a-menu-item>
                            </a-menu>
                        </template>
                    </a-dropdown>
                    <x-table-column-setting
                        ref="tableColumnSettingRef"
                        v-model:columns="columns">
                        <a-tooltip title="列设置">
                            <a-button type="text">
                                <template #icon>
                                    <setting-outlined></setting-outlined>
                                </template>
                            </a-button>
                        </a-tooltip>
                    </x-table-column-setting>
                </a-space>
            </template>
        </x-toolbar>
        <a-table
            :columns="columns[curList]"
            :data-source="listData"
            :loading="loading"
            :pagination="paginationState"
            :size="size"
            class="mt-8-2"
            row-key="id"
            @change="onTableChange">
            <template #bodyCell="{ column, record }">
                <template v-if="'action' === column.key">
                    <x-action-button
                        size="small"
                        @click="goDetail(record)"
                        >查看</x-action-button
                    >
                    <x-action-button @click="downloadFile(record)">导出</x-action-button>
                    <x-action-button
                        v-if="tableIndex == 0 && curList.includes('0')"
                        @click="goReport(record)"
                        >报告</x-action-button
                    >
                    <!-- <x-action-button @click="handleDelete(record)">报告</x-action-button> -->
                </template>
            </template>
        </a-table>
    </a-card>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useThemeToken } from '@/hooks'
import router from '@/router'
import {
    ColumnHeightOutlined,
    DownOutlined,
    PlusOutlined,
    ReloadOutlined,
    SettingOutlined,
    UpOutlined,
} from '@ant-design/icons-vue'
import apis from '@/apis'
import { config } from '@/config'
import { usePagination } from '@/hooks'
import { TableColumnSetting as XTableColumnSetting } from '@/components'
import { useRoute } from 'vue-router'
import { industryEnum, dataType } from '@/enums/industry'
defineOptions({ name: 'listTable' })
const { token } = useThemeToken()
const route = useRoute()
const curTable = route.path.split('/')[2]
const curList = route.path.split('/')[3]
const tableIndex = curTable.at(-1)
const curIndustry = industryEnum[curTable].children[curList]
const { getList } = tableIndex == 0 ? apis.list : apis.statement
const { listData, paginationState, loading, showLoading, hideLoading, resetPagination, searchFormData } =
    usePagination()
const columns = {
    list_0: [
        {
            title: '序号',
            key: 'no',
            width: 80,
            dataIndex: 'no',
            ignoreSetting: true,
            customRender: ({ index }) => index + 1,
        },
        { title: '统一社会信用代码', key: 'creditCode', dataIndex: 'creditCode' },
        { title: '单位名称', key: 'name', dataIndex: 'name' },
        // { title: '行业', key: 'industry', dataIndex: 'industry' },
        {
            title: `报出日期`,
            key: tableIndex == 0 ? 'year' : 'time',
            dataIndex: tableIndex == 0 ? 'year' : 'time',
        },
        { title: '差错数', key: 'errorCount', dataIndex: 'errorCount' },
        { title: '操作', key: 'action', width: 200 },
    ],
    list_1: [
        {
            title: '序号',
            key: 'no',
            width: 80,
            dataIndex: 'no',
            ignoreSetting: true,
            customRender: ({ index }) => index + 1,
        },
        { title: '统一社会信用代码', key: 'creditCode', dataIndex: 'creditCode' },
        { title: '单位名称', key: 'name', dataIndex: 'name' },
        // { title: '行业', key: 'industry', dataIndex: 'industry' },
        { title: '报出日期', key: tableIndex == 0 ? 'month' : 'time', dataIndex: tableIndex == 0 ? 'month' : 'time' },
        { title: '差错数', key: 'errorCount', dataIndex: 'errorCount' },
        { title: '操作', key: 'action', width: 200 },
    ],
}
const tableColumnSettingRef = ref()
const collapsed = ref(true)
const size = ref('default')
/**
 * 获取分页列表
 */
async function getPageList() {
    try {
        showLoading()
        const { pageSize, current } = paginationState
        const { code, data } = await getList[curList]({
            pageSize,
            pageNum: current,
            category: Number(tableIndex) + 1,
            type: curIndustry.type,
            ...searchFormData.value,
        }).catch(() => {
            throw new Error()
        })
        hideLoading()
        if (config('http.code.success') === code) {
            const { records, pagination } = data
            listData.value = records
            paginationState.total = pagination.total
        }
    } catch (error) {
        hideLoading()
    }
}

/**
 * 搜索
 */
function handleSearch() {
    resetPagination()
    getPageList()
}
function handleReset() {
    searchFormData.value = {}
    resetPagination()
    getPageList()
}

const goDetail = (record) => {
    const path = ['', route.path.split('/')[1], route.path.split('/')[2], `detail_${curList.at(-1)}`].join('/')
    router.push({ path, query: { id: record.id } })
}

const goReport = (record) => {
    const path = ['', route.path.split('/')[1], route.path.split('/')[2], 'report'].join('/')
    router.push({ path, query: { id: record.id } })
}
/**
 * 密度
 * @param {string} key
 */
function handleSize({ key }) {
    size.value = key
}

/**
 * 表格发生改变
 * @param current
 * @param pageSize
 */
function onTableChange({ current, pageSize }) {
    paginationState.current = current
    paginationState.pageSize = pageSize
    getPageList()
}
function downloadFile(record) {
    const link = document.createElement('a')
    const monthUrl = `${config('http.apiBasic')}/statement/month/${record.id}/download`
    const yearUrl = `${config('http.apiBasic')}/statement/${record.id}/download`
    link.href = curList.includes('0') ? yearUrl : monthUrl
    link.download = `${record.name}_企业报表文件`
    link.target = '_blank' // 可选，如果希望在新窗口中下载文件，请取消注释此行
    link.click()
}
onMounted(() => {
    if (listData.value.length > 0) return
    getPageList()
})
</script>

<style lang="less" scoped></style>
